<!--分散式房源编辑表单-->
<template>
	<a-form ref="form" class="house-form-base" :model="community" :rules="communityRules(community)" layout="vertical" scroll-to-first-error>
		<a-typography-text strong>
			<blockquote>经营模式</blockquote>
		</a-typography-text>
		<a-form-item name="houseBizMode">
			<a-radio-group v-model:value="community.houseBizMode" :disabled="community.houseBizMode===1 && houseBizModeDisabled" class="custom-radio-group">
				<a-radio-button v-for="item in houseBizModeList" :key="item.value" :value="item.value">
					<a-typography-paragraph>{{ item.label }}</a-typography-paragraph>
					<a-typography-text type="secondary">
						<small>{{ item.desc }}</small>
					</a-typography-text>
				</a-radio-button>
			</a-radio-group>
		</a-form-item>
		<a-typography-text strong>
			<blockquote>项目信息</blockquote>
		</a-typography-text>
		<a-row :gutter="16">
			<a-col :span="4">
				<a-form-item label="项目编号：" name="communityNo">
					<a-input v-model:value="community.communityNo" allow-clear :maxlength="15" placeholder="请输入项目编号" />
				</a-form-item>
			</a-col>
			<a-col :span="6">
				<a-form-item label="项目名称：" name="name">
					<a-input v-model:value="community.name" allow-clear :maxlength="20" placeholder="请输入项目名称" />
				</a-form-item>
			</a-col>
			<a-col :span="14">
				<a-form-item label="项目地址：" name="location">
					<a-form-item-rest>
						<a-input-group compact style="display: flex">
							<a-select v-model:value="community.cityId" v-bind="cityOptions" style="width: 200px" />
							<a-auto-complete v-model:value="community.address" v-bind="searchOptions" :disabled="!community.cityId" style="flex: 1">
								<template #notFoundContent>
									<a-spin v-if="loading.search" spinning tip="正在搜索，请稍候……" />
									<a-empty v-else description="暂无匹配数据，请确认地址输入是否正确" />
								</template>
								<template #option="item">
									{{ item.name }}
									<a-divider dashed class="margin-none" />
									<a-typography-text type="secondary">
										<small>{{ item.address }}</small>
									</a-typography-text>
								</template>
							</a-auto-complete>
						</a-input-group>
					</a-form-item-rest>
				</a-form-item>
			</a-col>
			<a-col :span="6">
				<a-form-item label="开业日期：" name="openingDate">
					<a-date-picker v-model:value="community.openingDate" allow-clear :value-format="DATE_FORMAT.DATE" placeholder="请选择开业日期" />
				</a-form-item>
			</a-col>
			<a-col :span="6">
				<a-form-item label="门店电话：" name="contactNumber">
					<a-input v-model:value="community.contactNumber" allow-clear :maxlength="15" placeholder="请选择门店电话" />
				</a-form-item>
			</a-col>
		</a-row>
		<a-typography-text strong>
			<blockquote>楼栋信息</blockquote>
		</a-typography-text>

		<a-skeleton :loading="loading.load" active>
			<a-form-item name="buildings">
				<a-form-item v-for="(building, i) in buildings" :key="building.id" :name="['buildings', i]" :rules="buildingRules">
					<a-form-item-rest>
						<a-input-group compact class="building-input-group">
							<a-input v-model:value="building.buildingNo" :maxlength="6" placeholder="请输入" style="flex: 1.2">
								<template #prefix>
									<a-typography-text type="danger">*</a-typography-text>
									楼栋
								</template>
							</a-input>
							<a-auto-complete v-model:value="building.buildingNoSuffix" :options="buildingSuffixes" style="flex: 0.7">
								<template #default>
									<a-input>
										<template #suffix>
											<down-outlined style="font-size: 12px; color: rgba(0, 0, 0, 0.25)" />
										</template>
									</a-input>
								</template>
							</a-auto-complete>
							<a-input v-model:value="building.unit" :maxlength="6" suffix="单元" placeholder="请输入" style="flex: 1" />
							<a-input-number v-model:value.number="building.totalFloor" :min="1" :max="300" :precision="0" :disabled="!!building.id" :controls="false" @input="onInputToGenFloors(building)" placeholder="请输入" style="flex: 1.5">
								<template #prefix>
									<a-typography-text type="danger">*</a-typography-text>
									共
								</template>
								<template #addonAfter>
									层&nbsp;&nbsp;
									<a :disabled="building.id" @click="showFloorConfig(building)">
										<setting-outlined />
									</a>
								</template>
							</a-input-number>
							<a-input-number v-model:value.number="building.perFloorRoomsTotal" :min="1" :max="300" :precision="0" :disabled="!!building.id" :controls="false" placeholder="请输入" style="flex: 1.5">
								<template #prefix>
									<a-typography-text type="danger">*</a-typography-text>
									每层
								</template>
								<template #addonAfter>间</template>
							</a-input-number>
							<a-input v-model:value="building.roomNoPrefix" :maxlength="6" :disabled="!!building.id || !building.hasRoomNoPrefix" style="flex: 3.5" placeholder="请输入">
								<template #addonBefore>
									<a-checkbox v-model:checked="building.hasRoomNoPrefix" :disabled="!!building.id">房号前缀</a-checkbox>
								</template>
								<template #addonAfter>
									<a-checkbox :checked="Boolean(building.isExcludeFour)" :disabled="!!building.id" @change="e => onExcludeFourChange(e, building)">
										<a-typography-text
											:ellipsis="{
												tooltip: true
											}"
											style="width: 100px; text-align: left"
											:content="`房号去 ${(building.noExcludeRules || []).map(o => o.num).join() || '-'}`" />
									</a-checkbox>
									<a :disabled="building.id" @click="showNoRuleConfig(building)">
										<form-outlined />
									</a>
								</template>
							</a-input>
							<a-tooltip title="删除楼栋">
								<a-button v-if="buildings.length > 1" type="link" danger @click="onClickToDelBuilding(building, i)">
									<delete-outlined />
								</a-button>
							</a-tooltip>
						</a-input-group>
					</a-form-item-rest>
				</a-form-item>

				<a-button type="primary" ghost block @click="onClickToAddBuilding" style="border-style: dashed">
					<plus-outlined />
					添加楼栋
				</a-button>
			</a-form-item>
		</a-skeleton>

		<a-typography-text strong>
			<blockquote>项目归属</blockquote>
		</a-typography-text>
		<a-row :gutter="16">
			<a-col :span="12">
				<a-form-item label="部门(门店)/维护人：" name="stewardId">
					<dept-emp-select v-model:dept-id="community.deptId" v-model:emp-id="community.stewardId" only-store />
				</a-form-item>
			</a-col>
		</a-row>
	</a-form>

	<teleport v-if="visibles.footer" to=".house-edit-dialog .ant-modal-footer">
		<a-button type="primary" :loading="loading.save" @click="saveCommunityBase()">保存</a-button>
		<a-button type="primary" ghost v-if="community.id" :loading="loading.save" @click="saveCommunityBase(true)">下一步，完善房间配置</a-button>
	</teleport>

	<!-- 楼层编辑 -->
	<floor-editing v-model:visible="visibles.editing" :building="currentBuilding" @submit="onFloorSubmit" />
	<room-number-special-configuration v-model:visible="visibles.dispose" :building="currentBuilding" @submit="onNoRuleSubmit" />
</template>

<script lang="ts" setup>
	import {createVNode, onMounted, reactive, ref, toRaw, watch, watchEffect} from 'vue'
	import {buildingSuffixes, houseBizModeList} from '@/interface/house'
	import houseApi from '@/api/house-api'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {DeleteOutlined, DownOutlined, FormOutlined, PlusOutlined, QuestionCircleOutlined, SettingOutlined} from '@ant-design/icons-vue'
	import {message, Modal} from 'ant-design-vue'
	import {COLOR_MAP, DEFAULT_FIELD_NAME} from 'yuxin-base/src/constant'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import {ownerContractCheckValid} from '@/api/contract'
	import {Building, Community, defaultBuilding, Floor} from '@/interface/community'
	import {communityRules} from '@/rules/community'
	import {Rule} from 'ant-design-vue/es/form'
	import {findSelf} from '@/utils'
	import {FormExpose} from 'ant-design-vue/lib/form/Form'
	import XEUtils from 'xe-utils'
	import RoomNumberSpecialConfiguration from '@/components/house/edit/centralized/room-number-special-configuration.vue'
	import floorEditing from '@/components/house/edit/centralized/floor-editing.vue'

	const props = defineProps<{
		value: Community
	}>()

	const form = ref<FormExpose>()
	// 项目信息
	const community = ref<Community>(props.value)

	const emits = defineEmits(['next','update'])
	const checkedIndex = ref<any>(null)

	const loading = reactive({
		save: false,
		load: false,
		search: false
	})

	const visibles = reactive<any>({
		footer: false,
		dispose: false,
		editing: false
	})

	// @ts-ignore
	const geocoder = new AMap.Geocoder({
		// city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
		city: community.value.cityName
	})

	const getAddress = (position: any[]) => {
		geocoder.getAddress(position, (status: string, result: any) => {
			const {
				info,
				regeocode: {addressComponent, formattedAddress}
			} = result

			if (status === 'complete' && info === 'OK') {
				const {district, township} = addressComponent
				community.value.areaName = district
				community.value.townName = township
				// if (formattedAddress) {
				// 	community.value.address = formattedAddress
				// }

				const area = areas.value.find((o: any) => o.name === community.value.areaName) || {}
				community.value.areaId = area.id

				console.log(result)
				console.log(toRaw(community.value))
			}
		})
	}

	// @ts-ignore
	let autocomplete: any = new AMap.Autocomplete({
		datatype: 'poi',
		citylimit: true
	})

	onMounted(() => {
		visibles.footer = true
		getBaseInfo()

		settingApi.getCityList().then(({data}) => (cities.value = data))
	})

	// 地址搜索结果
	const searchOptions = reactive<any>({
		options: [],
		allowClear: true,
		filterOption: false,
		placeholder: '请输入项目地址搜索',
		onSearch(keyword: string) {
			if (autocomplete && keyword) {
				searchAddress(keyword)
			}
		},
		onSelect(value: string, option: any) {
			community.value.address = option.address
			community.value.lat = option.location.lat
			community.value.lng = option.location.lng

			const pos = [option.location.lng, option.location.lat]

			// 获取区域、街道、详细地址
			getAddress(pos)
		}
	})

	const searchAddress = XEUtils.debounce((keyword: string) => {
		loading.search = true
		searchOptions.options = []
		autocomplete.search(keyword, (status: string, result: any) => {
			loading.search = false
			const tips = result.tips || []

			for (let tip of tips) {
				tip.value = tip.address
			}

			searchOptions.options = result.tips || []
		})
	}, 300)

	const buildingRules: Rule[] = [
		{
			validator(rule: any, value: Building) {
				if (value.buildingNo && value.totalFloor && value.perFloorRoomsTotal) {
					return Promise.resolve()
				} else {
					return Promise.reject('请完善楼栋信息')
				}
			}
		}
	]

	// 楼栋列表
	const buildings = ref<Building[]>(community.value.buildings || [])

	// 获取项目信息
	const getBaseInfo = (type?:string) => {
		if (community.value.id) {
			loading.load = true
			// 获取项目详情
			houseApi
				.getProjectBasicInfo(community.value.id)
				.then(({data}) => {
					const buildingBasicInfoList: Building[] = data.buildingBasicInfoList

					for (let item of buildingBasicInfoList) {
						item.hasRoomNoPrefix = !!item.roomNoPrefix
					}

					community.value = data.community
					buildings.value = buildingBasicInfoList
					community.value.buildings = buildings.value
					if(community.value.houseBizMode==1){
						getOwnerContractCheckValid()
					}
					if(type){
						emits('update',community.value)
					}
					searchAddress(community.value.name)
				})
				.finally(() => (loading.load = false))
		}
	}
	const houseBizModeDisabled = ref<boolean>(false)
	const getOwnerContractCheckValid = ()=>{
		ownerContractCheckValid(community.value.id).then(res=>{
			houseBizModeDisabled.value = res.data
			console.log(res,'是否有业主合同')
		})
	}

	// 城市列表
	const cities = ref<any>([])
	const cityOptions = reactive<any>({
		options: cities,
		allowClear: true,
		showSearch: true,
		placeholder: '请选择城市',
		optionFilterProp: 'name',
		fieldNames: DEFAULT_FIELD_NAME,
		onChange() {
			// 切换城市后清空地址搜索
			searchOptions.options = []
			// 更新地图搜索区域
			autocomplete.setCity(community.value.regionCode)
		}
	})

	// 区域列表
	const areas = ref<any[]>([])
	watchEffect(async () => {
		// console.log(props.value.)
		const city = findSelf(cities.value, community.value.cityId) || {}

		community.value.cityName = city.name
		community.value.regionCode = city.regionCode

		if (community.value.cityId) {
			const {data} = await settingApi.getAreaListByCityId(community.value.cityId)
			const area = data.find((o: any) => o.name === community.value.areaName) || {}
			areas.value = data
			community.value.areaId = area.id

			if (autocomplete) {
				autocomplete.setCity(city.regionCode)
			}
		} else {
			community.value.address = null
		}
	})

	// 街道列表
	const towns = ref<any[]>([])
	watchEffect(async () => {
		if (community.value.areaId) {
			const {data} = await settingApi.getTownListByAreaId(community.value.areaId)
			const town = data.find((o: any) => o.name === community.value.townName) || {}

			towns.value = data
			community.value.townId = town.id
		}
	})

	// 当前编辑的楼栋
	const currentBuilding = ref<Building>(defaultBuilding())

	watch(currentBuilding.value, () => {
		if (currentBuilding.value.id) {
			console.log(currentBuilding.value)
		}
	})

	/**
	 * 生成楼层
	 */
	const genFloors = () => {
		// 生成楼层
		currentBuilding.value.floorList = Array.from(new Array(currentBuilding.value.totalFloor || 1)).map((v, i) => ({
			floor: i + 1,
			floorNo: i + 1,
			disabled: 0
		}))
	}

	/**
	 * 生成当前楼栋楼层
	 * @param building
	 */
	const onInputToGenFloors = (building: Building) => {
		currentBuilding.value = building
		genFloors()
	}

	const showFloorConfig = (building: Building) => {
		if (!building.id) {
			currentBuilding.value = building
			visibles.editing = true
		}
	}

	const onFloorSubmit = (floors: Floor[]) => {
		currentBuilding.value.floorList = floors
	}

	const onExcludeFourChange = (e: any, building: Building) => {
		const {target} = e
		// console.log(building, target)
		building.isExcludeFour = Number(target.checked)
	}

	const showNoRuleConfig = (building: Building) => {
		if (!building.id) {
			currentBuilding.value = building
			visibles.dispose = true
		}
	}

	// 默认房间号排除规则
	const onNoRuleSubmit = (isDefault: boolean) => {
		if (isDefault) {
			community.value.roomNoRule = {
				noExcludeRules: currentBuilding.value.noExcludeRules
			}
		}
	}

	/**
	 * 生成房间
	 */
	const generateRooms = () => {
		const reqs = buildings.value
			.filter(o => !o.id)
			.flatMap(building =>
				building.floorList?.map(floor => {
					const params = {
						genFloor: floor.floorNo,
						highestFloor: building.totalFloor,
						perFloorRoomsCount: building.perFloorRoomsTotal,
						roomNoPrefix: building.roomNoPrefix,
						roomNoRuleConfig: building.isExcludeFour ? building.noExcludeRules || [] : []
					}
					return houseApi.roomNumberGenerator(params).then(({data}: any) => {
						floor.roomList = data[0].roomNoList.map((roomNo: string) => ({
							roomNo,
							disabled: 0
						}))
					})
				})
			)

		return Promise.all(reqs)
	}

	/**
	 * 添加楼栋
	 */
	const onClickToAddBuilding = () => {
		const building = defaultBuilding()

		if (community.value.roomNoRule?.noExcludeRules) {
			building.noExcludeRules = community.value.roomNoRule.noExcludeRules.filter(o => o)
		}

		buildings.value.push(building)
	}

	/**
	 * 删除楼栋
	 */
	const onClickToDelBuilding = (building: Building, index: number) => {
		Modal.confirm({
			width: 470,
			title: '系统提示',
			content: () =>
				createVNode('div', {}, [
					createVNode('div', {
						innerHTML: '请确定相关房间的在租合约、固定资产、智能设备已清空'
					}),
					createVNode('div', {
						innerHTML: '楼栋删除后无法恢复, 确定删除',
						style: {
							color: COLOR_MAP.danger
						}
					})
				]),
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			okText: '删除',
			okType: 'danger',
			async onOk() {
				if (building.id) {
					await houseApi.removeBuilding(building.id)
				}
				buildings.value.splice(index, 1)
				message.success('楼栋删除成功')
			}
		})
	}

	/**
	 * 保存项目基础信息
	 */
	const saveCommunityBase = (next?: boolean) => {
		form.value
			?.validate()
			.then(() => {
				loading.save = true
				generateRooms()
					.then(() => {
						loading.save = true

						houseApi[community.value.id ? 'updateProjectBasicInfo' : 'addProjectBasicInfo']({
							communityForm: community.value,
							buildingFormList: buildings.value
						})
							.then(({data}) => {
								if (data) {
									community.value.id = data
								}
								message.success('楼盘信息保存成功')
								next ? emits('next',community.value) : getBaseInfo('next')
							})
							.finally(() => (loading.save = false))
					})
					.finally(() => (loading.save = false))
			})
			.catch(({errorFields}) => {
				form.value?.scrollToField(errorFields[0].name, {
					behavior: 'smooth'
				})
			})
	}
</script>

<style lang="less" scoped>
	.house-form-base {
		.custom-radio-group {
			display: flex;
			justify-content: space-between;

			label {
				width: 25%;
				margin-right: 15px;
			}
			label:nth-child(4) {
				width: 25%;
				margin-right: 0px;
			}
		}

		:deep(.ant-form-item) {
			.ant-input-prefix,
			.ant-input-number-prefix,
			.ant-input-number-group-addon {
				color: inherit;
			}
		}

		.ant-skeleton {
			width: 100%;
		}

		.building-input-group {
			display: flex;
		}
	}
</style>
